import {
  CoolController,
  BaseController,
  CoolUrlTag,
  TagTypes,
} from '@cool-midway/core';
import { GoodsInfoEntity } from '../../entity/info';
import { GoodsInfoService } from '../../service/info';
import { GoodsTypeEntity } from '../../entity/type';
import { GoodsBatchEntity } from '../../entity/batch.entity';
import { In, Repository } from 'typeorm';
import { Body, Post, Inject } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';

/**
 * 商品信息
 */
@CoolUrlTag({
  key: TagTypes.IGNORE_TOKEN,
  value: ['page', 'info', 'pageWithValDate'],
})
@CoolController({
  api: ['page', 'info'],
  entity: GoodsInfoEntity,
  service: GoodsInfoService,
  pageQueryOp: {
    keyWordLikeFields: [
      'title',
      'goodsCode',
      'oracleGoodsName',
      'manufacturer',
      'goodsCode',
      'logogram'
    ],
    fieldEq: ['a.typeId'],
    select: ['a.*', 'b.name as typeName'],
    where: ctx => {
      const { minPrice, maxPrice, attribute, typeIds } = ctx.request.body;
      const conditions = [
        // 过滤掉已下架商品
        ['a.status = :status', { status: 1 }],
        ['a.storNum > :storNum', { storNum: 0 }],
        // 价格区间
        ['a.price >= :minPrice', { minPrice }, minPrice],
        ['a.price <= :maxPrice', { maxPrice }, maxPrice],
      ];

      // 处理多选属性查询
      if (attribute && attribute.length > 0) {
        const attributes = attribute.toString().split(',');
        const attrConditions = attributes.map(attr => {
          return [
            `a.attribute LIKE :attr${attr}`,
            { [`attr${attr}`]: `%${attr}%` },
          ];
        });
        if (attrConditions.length > 0) {
          conditions.push([
            '(' + attrConditions.map(([sql]) => sql).join(' OR ') + ')',
            attrConditions.reduce(
              (params, [_, param]) => ({ ...params, ...param }),
              {}
            ),
          ]);
        }
      }

      // 处理商品类型多选查询
      if (typeIds && typeIds.length > 0) {
        const typeIdList = typeIds
          .toString()
          .split(',')
          .map(Number)
          .filter(id => !isNaN(id));
        if (typeIdList.length > 0) {
          conditions.push(['a.typeId IN (:typeIdList)', { typeIdList }]);
        }
      }

      return conditions;
    },
    join: [
      {
        entity: GoodsTypeEntity,
        alias: 'b',
        condition: 'a.typeId = b.id',
      }
    ],
  },
})
export class AppGoodsInfoController extends BaseController {
  @InjectEntityModel(GoodsInfoEntity)
  goodsInfoEntity: Repository<GoodsInfoEntity>;

  @Inject()
  goodsInfoService: GoodsInfoService;

  @Post('/pageWithValDate')
  async pageWithValDate(@Body() params) {
    return this.ok(await this.goodsInfoService.pageWithValDate(params));
  }
}
